package de.luhmer.owncloudnewsreader.database.model;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** 
 * DAO for table "FEED".
*/
public class FeedDao extends AbstractDao<Feed, Long> {

    public static final String TABLENAME = "FEED";

    /**
     * Properties of entity Feed.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property Id = new Property(0, long.class, "id", true, "_id");
        public final static Property FolderId = new Property(1, Long.class, "folderId", false, "FOLDER_ID");
        public final static Property FeedTitle = new Property(2, String.class, "feedTitle", false, "FEED_TITLE");
        public final static Property FaviconUrl = new Property(3, String.class, "faviconUrl", false, "FAVICON_URL");
        public final static Property Link = new Property(4, String.class, "link", false, "LINK");
        public final static Property AvgColour = new Property(5, String.class, "avgColour", false, "AVG_COLOUR");
    };

    private DaoSession daoSession;

    private Query<Feed> folder_FeedListQuery;

    public FeedDao(DaoConfig config) {
        super(config);
    }
    
    public FeedDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /** Creates the underlying database table. */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "\"FEED\" (" + //
                "\"_id\" INTEGER PRIMARY KEY NOT NULL ," + // 0: id
                "\"FOLDER_ID\" INTEGER," + // 1: folderId
                "\"FEED_TITLE\" TEXT NOT NULL ," + // 2: feedTitle
                "\"FAVICON_URL\" TEXT," + // 3: faviconUrl
                "\"LINK\" TEXT," + // 4: link
                "\"AVG_COLOUR\" TEXT);"); // 5: avgColour
        // Add Indexes
        db.execSQL("CREATE INDEX " + constraint + "IDX_FEED_FOLDER_ID ON FEED" +
                " (\"FOLDER_ID\");");
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"FEED\"";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, Feed entity) {
        stmt.clearBindings();
        stmt.bindLong(1, entity.getId());
 
        Long folderId = entity.getFolderId();
        if (folderId != null) {
            stmt.bindLong(2, folderId);
        }
        stmt.bindString(3, entity.getFeedTitle());
 
        String faviconUrl = entity.getFaviconUrl();
        if (faviconUrl != null) {
            stmt.bindString(4, faviconUrl);
        }
 
        String link = entity.getLink();
        if (link != null) {
            stmt.bindString(5, link);
        }
 
        String avgColour = entity.getAvgColour();
        if (avgColour != null) {
            stmt.bindString(6, avgColour);
        }
    }

    @Override
    protected void attachEntity(Feed entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    /** @inheritdoc */
    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.getLong(offset + 0);
    }    

    /** @inheritdoc */
    @Override
    public Feed readEntity(Cursor cursor, int offset) {
        Feed entity = new Feed( //
            cursor.getLong(offset + 0), // id
            cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1), // folderId
            cursor.getString(offset + 2), // feedTitle
            cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // faviconUrl
            cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // link
            cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5) // avgColour
        );
        return entity;
    }
     
    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, Feed entity, int offset) {
        entity.setId(cursor.getLong(offset + 0));
        entity.setFolderId(cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1));
        entity.setFeedTitle(cursor.getString(offset + 2));
        entity.setFaviconUrl(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
        entity.setLink(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
        entity.setAvgColour(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
     }
    
    /** @inheritdoc */
    @Override
    protected Long updateKeyAfterInsert(Feed entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }
    
    /** @inheritdoc */
    @Override
    public Long getKey(Feed entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override    
    protected boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "feedList" to-many relationship of Folder. */
    public List<Feed> _queryFolder_FeedList(Long folderId) {
        synchronized (this) {
            if (folder_FeedListQuery == null) {
                QueryBuilder<Feed> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.FolderId.eq(null));
                folder_FeedListQuery = queryBuilder.build();
            }
        }
        Query<Feed> query = folder_FeedListQuery.forCurrentThread();
        query.setParameter(0, folderId);
        return query.list();
    }

    private String selectDeep;

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getFolderDao().getAllColumns());
            builder.append(" FROM FEED T");
            builder.append(" LEFT JOIN FOLDER T0 ON T.\"FOLDER_ID\"=T0.\"_id\"");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }
    
    protected Feed loadCurrentDeep(Cursor cursor, boolean lock) {
        Feed entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        Folder folder = loadCurrentOther(daoSession.getFolderDao(), cursor, offset);
        entity.setFolder(folder);

        return entity;    
    }

    public Feed loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();
        
        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);
        
        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }
    
    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<Feed> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<Feed> list = new ArrayList<Feed>(count);
        
        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<Feed> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    

    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<Feed> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
 
}
